import React, { useState, useEffect, useRef } from 'react';
import { 
  Button, 
  message, 
  Modal, 
  Table, 
  Space, 
  Input, 
  Form, 
  Upload, 
  Image,
  Popconfirm,
  Tag
} from 'antd';
import { 
  PlusOutlined, 
  DeleteOutlined, 
  EditOutlined, 
  UploadOutlined,
  SearchOutlined,
  GlobalOutlined,
  DownloadOutlined,
  SettingOutlined
} from '@ant-design/icons';
import { getPlanetList, createPlanet, updatePlanet, deletePlanet, uploadPlanetImage, setDefaultPlanet, PlanetItem } from '../api/gis';
import { useNavigate } from 'react-router-dom';
import Breadcrumb from '@/components/Breadcrumb';
import './DataManagement.css';

const { Search } = Input;

const GISManagement: React.FC = () => {
  const navigate = useNavigate();
  const [planets, setPlanets] = useState<PlanetItem[]>([]);
  const [loading, setLoading] = useState(false);

  const [modalVisible, setModalVisible] = useState(false);
  const [editingPlanet, setEditingPlanet] = useState<PlanetItem | null>(null);
  const [uploadModalVisible, setUploadModalVisible] = useState(false);
  const [uploadingPlanetId, setUploadingPlanetId] = useState<number | null>(null);
  const [form] = Form.useForm();
  const [editForm] = Form.useForm();
  const [uploadForm] = Form.useForm();

  
  // 分页状态
  const [current, setCurrent] = useState(1);
  const [pageSize, setPageSize] = useState(20);
  const [total, setTotal] = useState(0);

  // 表格容器ref和滚动高度
  const tableContainerRef = useRef(null);
  const [tableScrollY, setTableScrollY] = useState(0);

  // 获取星球列表
  const fetchPlanets = async (page = 1, size = 20, filters = {}) => {
    setLoading(true);
    try {
      const formValues = form.getFieldsValue();
      const response = await getPlanetList({
        page,
        page_size: size,
        planet_name: formValues.planet_name || '',
        ...filters
      });
      
      if (response.code === 200) {
        setPlanets(response.data.list);
        setTotal(response.data.count);
        setCurrent(response.data.page);
        setPageSize(response.data.page_size);
      } else {
        message.error(response.msg || '获取星球列表失败');
      }
    } catch (error) {
      console.error('获取星球列表失败:', error);
      message.error(error?.message || '获取星球列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时获取数据
  useEffect(() => {
    fetchPlanets();
  }, []);

  // 筛选表单提交
  const onFinish = () => {
    setCurrent(1);
    fetchPlanets(1, pageSize);
  };



  // 分页处理
  const handleTableChange = (paginationInfo: any) => {
    setCurrent(paginationInfo.current);
    setPageSize(paginationInfo.pageSize);
    fetchPlanets(paginationInfo.current, paginationInfo.pageSize);
  };

  // 新建星球
  const handleCreate = () => {
    setEditingPlanet(null);
    editForm.resetFields();
    setModalVisible(true);
  };

  // 编辑星球
  const handleEdit = (record: PlanetItem) => {
    setEditingPlanet(record);
    editForm.setFieldsValue({
      planet_name: record.planet_name,
      planet_name_zh: record.planet_name_zh,
      radius: record.radius
    });
    setModalVisible(true);
  };

  // 跳转到详情页面
  const handleDetail = (record: PlanetItem) => {
    navigate(`/gis-detail?id=${record.id}`);
  };

  // 删除星球
  const handleDelete = async (record: PlanetItem) => {
    Modal.confirm({
      title: '确认删除',
      content: `确定要删除星球 "${record.planet_name_zh}" 吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await deletePlanet({ id: record.id });
          if (response.code === 200) {
            message.success('删除成功');
            fetchPlanets(current, pageSize);
          } else {
            message.error(response.msg || '删除失败');
          }
        } catch (error) {
          console.error('删除星球失败:', error);
          message.error(error?.message || '删除失败');
        }
      }
    });
  };

  // 设置默认星球
  const handleSetDefault = async (record: PlanetItem) => {
    Modal.confirm({
      title: '确认设置默认',
      content: `确定要将星球 "${record.planet_name_zh}" 设为默认星球吗？`,
      okText: '确认',
      cancelText: '取消',
      onOk: async () => {
        try {
          const response = await setDefaultPlanet({ id: record.id });
          if (response.code === 200) {
            message.success('设置默认星球成功');
            fetchPlanets(current, pageSize);
          } else {
            message.error(response.msg || '设置默认星球失败');
          }
        } catch (error) {
          console.error('设置默认星球失败:', error);
          message.error(error?.message || '设置默认星球失败');
        }
      }
    });
  };

  // 保存星球（新建或编辑）
  const handleSave = async () => {
    try {
      const values = await editForm.validateFields();
      
      if (editingPlanet) {
        // 编辑
        const response = await updatePlanet({
          id: editingPlanet.id,
          ...values
        });
        if (response.code === 200) {
          message.success('修改成功');
          setModalVisible(false);
          fetchPlanets(current, pageSize);
        } else {
          message.error(response.msg || '修改失败');
        }
      } else {
        // 新建
        const response = await createPlanet(values);
        if (response.code === 200) {
          message.success('创建成功');
          setModalVisible(false);
          fetchPlanets(current, pageSize);
        } else {
          message.error(response.msg || '创建失败');
        }
      }
    } catch (error) {
      console.error('保存星球失败:', error);
      message.error(error?.message || '保存失败');
    }
  };

  // 上传图片
  const handleUpload = (record: PlanetItem) => {
    setUploadingPlanetId(record.id);
    uploadForm.resetFields();
    setUploadModalVisible(true);
  };

  // 确认上传图片
  const handleUploadConfirm = async () => {
    try {
      const values = await uploadForm.validateFields();
      const response = await uploadPlanetImage({
        file: values.file[0].originFileObj,
        planet_id: uploadingPlanetId!
      });
      
      if (response.code === 200) {
        message.success('上传成功');
        setUploadModalVisible(false);
        fetchPlanets(current, pageSize);
      } else {
        message.error(response.msg || '上传失败');
      }
    } catch (error) {
      console.error('上传图片失败:', error);
      message.error(error?.message || '上传失败');
    }
  };



  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      ellipsis: true,
    },
    {
      title: '星球名称',
      dataIndex: 'planet_name',
      key: 'planet_name',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '中文名称',
      dataIndex: 'planet_name_zh',
      key: 'planet_name_zh',
      width: 150,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '半径(km)',
      dataIndex: 'radius',
      key: 'radius',
      width: 120,
      ellipsis: true,
      render: (radius: number) => radius ? `${radius}km` : '-',
    },
    {
      title: '是否默认',
      dataIndex: 'is_default',
      key: 'is_default',
      width: 100,
      ellipsis: true,
      render: (isDefault: number) => (
        <Tag color={isDefault === 1 ? 'green' : 'default'}>
          {isDefault === 1 ? '是' : '否'}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 180,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '更新时间',
      dataIndex: 'update_time',
      key: 'update_time',
      width: 180,
      ellipsis: true,
      render: (text) => (text === undefined || text === null || text === '' ? '-' : text)
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      align: 'center' as const,
      render: (_: any, record: PlanetItem) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            size="small"
            icon={<SettingOutlined />}
            onClick={() => handleDetail(record)}
          >
            详情
          </Button>
          {record.is_default !== 1 && (
            <Button
              type="link"
              size="small"
              icon={<GlobalOutlined />}
              onClick={() => handleSetDefault(record)}
            >
              设为默认
            </Button>
          )}
          <Button
            type="link"
            size="small"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];



  // 计算表格滚动高度
  const calculateTableScrollHeight = () => {
    if (tableContainerRef.current) {
      const containerHeight = tableContainerRef.current.clientHeight;
      const tableHeaderHeight = 89;
      const scrollHeight = containerHeight - tableHeaderHeight;
      setTableScrollY(scrollHeight);
      const body = tableContainerRef.current.querySelector('.ant-table-body');
      if (body) {
        body.style.height = Math.max(scrollHeight, 0) + 'px';
      }
    }
  };

  useEffect(() => {
    calculateTableScrollHeight();
    window.addEventListener('resize', calculateTableScrollHeight);
    return () => {
      window.removeEventListener('resize', calculateTableScrollHeight);
    };
  }, []);

  return (
    <div className="data-management-container">
      <div style={{ position: 'absolute', width: '100%', display: 'flex', flexDirection: 'column', height: '100%' }}>
        <Breadcrumb text="GIS星球管理" />
        <div className="content">
          {/* 筛选表单 */}
          <Form form={form} layout="inline" className="filter-form" onFinish={onFinish} labelCol={{ style: { width: 80 } }}>
            <Form.Item name="planet_name" label="星球名称" style={{ width: 350 }}>
              <Input placeholder="请输入星球名称搜索" />
            </Form.Item>
            <Form.Item style={{ paddingLeft: 40 }}>
              <Space>
                <Button type="primary" htmlType="submit">
                  筛选
                </Button>
                <Button
                  htmlType="button"
                  onClick={() => {
                    form.resetFields();
                    fetchPlanets(1, pageSize);
                  }}>
                  清除
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </div>



        {/* 操作按钮 */}
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
          <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
            新建星球
          </Button>
        </div>

        {/* 数据表格 */}
        <div className="pds-table-container" ref={tableContainerRef} style={{ flex: 1, overflow: 'hidden' }}>
          <Table
            columns={columns}
            dataSource={planets}
            rowKey="id"
            loading={loading}
            pagination={{
              current,
              pageSize,
              total,
              showSizeChanger: true,
              pageSizeOptions: ['10', '20', '50'],
              onChange: (page, size) => {
                setCurrent(page);
                setPageSize(size);
              },
              showTotal: (total) => `共 ${total} 条`
            }}
            scroll={{ y: tableScrollY, x: 'max-content' }}
            bordered
            size="small"
            onChange={handleTableChange}
          />
        </div>
      </div>

      {/* 新建/编辑星球弹窗 */}
      <Modal
        title={editingPlanet ? '编辑星球' : '新建星球'}
        open={modalVisible}
        onOk={handleSave}
        onCancel={() => setModalVisible(false)}
        width={600}
        okText="保存"
        cancelText="取消"
      >
        <Form
          form={editForm}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item
            name="planet_name"
            label="星球名称"
            rules={[{ required: true, message: '请输入星球名称' }]}
          >
            <Input placeholder="请输入星球名称（英文）" />
          </Form.Item>
          <Form.Item
            name="planet_name_zh"
            label="中文名称"
            rules={[{ required: true, message: '请输入中文名称' }]}
          >
            <Input placeholder="请输入中文名称" />
          </Form.Item>
          <Form.Item
            name="radius"
            label="半径（公里）"
            rules={[
              { required: true, message: '请输入半径' },
              {
                pattern: /^(\d+)(\.\d+)?$/,
                message: '请输入有效的数字（支持小数）'
              }
            ]}
          >
            <Input
              type="number"
              step="any"
              placeholder="请输入半径"
              min="0"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 上传图片弹窗 */}
      <Modal
        title="上传星球底图"
        open={uploadModalVisible}
        onOk={handleUploadConfirm}
        onCancel={() => setUploadModalVisible(false)}
        width={500}
        okText="上传"
        cancelText="取消"
      >
        <Form
          form={uploadForm}
          layout="vertical"
          style={{ marginTop: 16 }}
        >
          <Form.Item
            name="file"
            label="选择图片文件"
            rules={[{ required: true, message: '请选择图片文件' }]}
          >
            <Upload
              beforeUpload={() => false}
              maxCount={1}
              accept="image/*"
            >
              <Button icon={<UploadOutlined />}>选择文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default GISManagement; 